package com.yfcloud.middleware.storage.datanode;

import com.alibaba.fastjson.JSONObject;
import com.yfcloud.middleware.storage.datanode.listener.impl.PeseidonZkListener;
import com.yfcloud.middleware.storage.datanode.meta.MetaEntity;
import com.yfcloud.middleware.storage.tools.CommonUtil;
import com.yfcloud.middleware.storage.tools.Constant;
import com.yfcloud.middleware.storage.tools.ZKClientUtil;
import org.apache.zookeeper.CreateMode;

import java.net.UnknownHostException;
import java.util.Date;

public class ZookeeperRegistry{

    public ZookeeperRegistry init() {
        boolean flg = false;
        try{
            // 初始化子节点
            initDataNode();
            // 设置数据监听
            ZKClientUtil.RegistryListen(Constant.ALIVE_NODE_HASH,new PeseidonZkListener());
            flg = true;
        }catch (Exception ex){
            System.out.println(ex.getMessage());
        }finally {
            return this;
        }
    }

    // 初始化数据
    private MetaEntity initAliveEntity(){
        MetaEntity entity = new MetaEntity();
        entity.setStatus(Constant.NODE_STATUS.ALIVE.toString());
        entity.setLastUpdateTime(new Date().getTime());
        return entity;
    }

    // 初始化子节点
    private void initDataNode() throws UnknownHostException {

        MetaEntity entity = initAliveEntity();
        // 初始化子节点
        if(ZKClientUtil.isExistNode(Constant.ALIVE_NODE_HASH)){
            String value = ZKClientUtil.getNodeData(Constant.ALIVE_NODE_HASH);
            JSONObject jsonObject = JSONObject.parseObject(value);
            jsonObject.put(CommonUtil.getAddress(), entity);
            ZKClientUtil.setNodeData(Constant.ALIVE_NODE_HASH,jsonObject.toJSONString());
        }else{
            JSONObject jsonResult = new JSONObject();
            jsonResult.put(CommonUtil.getAddress(), entity);
            ZKClientUtil.createNodeAndData(CreateMode.PERSISTENT,Constant.ALIVE_NODE_HASH,jsonResult.toJSONString());
        }
    }

    private void CreateRootPath(){
        if(!ZKClientUtil.isExistNode(Constant.ZOOKEEPER_ROOT_PATH)){
            ZKClientUtil.createNode(CreateMode.PERSISTENT,Constant.ZOOKEEPER_ROOT_PATH);
        }
    }

    public ZookeeperRegistry syncMetadata() {
        return this;
    }

    public ZookeeperRegistry checkChild() {
        return this;
    }

    public class Builder(){

    }
}
